﻿/*
 * Create By:Jeff Yuan
 * Create Time : 2009-03-16 11:30
 * 
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using Jumpton.SFA.Server.Entity;
using Jumpton.Persistent;
using Jumpton.SFA.Server.BusinessRule;
using Jumpton.Data;
namespace Jumpton.SFA.Server.BusinessRule.System
{
    public enum LogType
    {
        ALERT_SECURITY,
        ALERT_TOOL,
        CUSTOM_TABLE,
        CUSTOM_TABLE_GROUP,
        CUSTOM_TABLE_INPUTTYPE,
        CUSTOM_TABLE_ITEM,
        CUSTOM_PROFILE,
        DICTIONARY,
        EXCEPTION,
        GENERAL_EXCEPTION,
        LOGIN_FAILURE,
        LOGIN_SUCCESS,
        LOGIN_USERLOCKEDOUT,
        LOGIN_USERNOTAPPROVED,
        LOG_NOTIFICATION_FAILURE,
        MAINTAIN_CATEGORY,
        PAGE_LOAD_EXCEPTION,
        PASSWOD_CHANGED,
        ROLE_CREATED,
        ROLE_DELETED,
        ROLE_UPDATED,
        SMS_MESSAGE,
        TAB_UPDATED,
        USER_CREATED,
        USER_DELETED,
        USER_UPDATED,
        USER_DOWNLOAD,//用户查询下载数据
        AUTOSYNC, // 数据库中数据自动同步产生的日志
        SENDMESSAGE, // 发送短信
        CSV_INPUT,  //CSV文件导入
        Info_Change
    }
    public class EventManager
    {
        #region IBusinessLogic 实现

        #region 保存

        public void Save(EventLog eventlog)
        {

            if (eventlog != null)
            {
                try
                {
                    //if (eventlogtype.State == DataRowState.Added)
                    //    eventlogtype.LogGUID = Common.KeyFactoryManager.GetCurrentValue("EventLog", 0).ToString() ;
                    eventlog.LogProperties = "  ";
                    //eventlog.LASTUPDATEDT = DateTime.Now.ToString("yyyyMMddHHmmss")
                    //eventlog.LASTUPDATEEMPLOYEEID = "null";
                    //eventlog.CREATEDT = DateTime.Now.ToString("yyyyMMddHHmmss");
                    //eventlog.CREATEEMPLOYEEID = "null";
                    //eventlog.ACTIVE = "1";
                    EventLog objx = ObjectRow.Load(typeof(EventLog), string.Format("LogGUID='{0}'", eventlog.LogGUID)) as EventLog;
                    if (objx != null)
                    {

                        // eventlog.LogGUID = DateTime.Now.ToString("yyyyMMddHHmmfffffff")+new Random().Next(1,1000);//以时间为主键
                        eventlog.LogGUID = Guid.NewGuid().ToString();
                    }
                    eventlog.Save();


                }
                catch (Exception error)
                {
                    throw new Exception(error.Message);
                }
            }

        }
        #endregion

        #region 获得一条数据


        #endregion

        #region 获得唯一性代码数据

        public EventLog LoadByCode(string Code)
        {
            return (EventLog)ObjectRow.Load(typeof(EventLog), "LogGUID='" + Code + "'");
        }
        #endregion

        #region 获得一组数据

        public ObjectTable LoadWithCondition(string Condition)
        {
            return new ObjectTable(typeof(EventLog), Condition);
        }
        #endregion

        #endregion

        #region 日志生成

        /// <summary>
        /// 通过枚举使用常用的类型进行日志保存
        /// </summary>
        /// <param name="logtype"></param>
        /// <param name="username"></param>
        /// <param name="userid"></param>
        /// <param name="content"></param>
        public static void CreateNewEvent(LogType logtype, string username, string userid, string content)
        {
            CreateNewEvent(logtype.ToString(), username, userid, content, DateTime.Now, Environment.MachineName.ToString(), "");
        }
        /// <summary>
        ///  通过枚举使用常用的类型进行日志保存 properties字段为备注可无限长
        /// </summary>
        /// <param name="logtype"></param>
        /// <param name="username"></param>
        /// <param name="userid"></param>
        /// <param name="content"></param>
        /// <param name="properties"></param>
        public static void CreateNewEvent(LogType logtype, string username, string userid, string content, string properties)
        {
            CreateNewEvent(logtype.ToString(), username, userid, content, DateTime.Now, Environment.MachineName.ToString(), properties);
        }
        /// <summary>
        /// 如果枚举中没有所需要的类型可以自定义一个类型
        /// logtypekey为自行输入的日志类型名
        /// </summary>
        /// <param name="logtypekey"></param>
        /// <param name="username"></param>
        /// <param name="userid"></param>
        /// <param name="content"></param>
        public static void CreateNewEvent(string logtypekey, string username, string userid, string content)
        {
            CreateNewEvent(logtypekey, username, userid, content, DateTime.Now, Environment.MachineName.ToString(), "");
        }


        public static void CreateNewEvent(string logtypekey, string username, string userid, string content, DateTime createdate, string servername, string properties)
        {
            if (!EventLogTypesManager.IsExistsLogTypeKey(logtypekey))
            {
                EventLogTypes elt = new EventLogTypes();
                elt.LogTypeKey = logtypekey;
                elt.LogTypeFriendlyName = logtypekey.Replace("_", " ").ToLower();
                elt.LogTypeOwner = Environment.MachineName;
                elt.LogTypeCSSClass = logtypekey;
                elt.LogTypeDescription = logtypekey;
                elt.Save();
            }
            EventLog eventlog = new EventLog();
            eventlog.LogCreateDate = createdate;
            eventlog.LogUserID = userid;
            eventlog.LogUserName = username;
            eventlog.LogTypeKey = logtypekey;
            eventlog.LogProperties = properties;
            eventlog.Content = content;
            eventlog.LogServerName = servername;
            eventlog.Content = content;
            new EventManager().Save(eventlog);
        }

        #endregion


        /// <summary>
        /// 日志查看的查询方法函数
        /// </summary>
        /// <param name="loginname"></param>
        /// <param name="logtypekey"></param>
        /// <param name="startdate"></param>
        /// <param name="enddate"></param>
        /// <returns></returns>
        public DataTable SelectInfo(string loginname, string logtypekey, DateTime startdate, DateTime enddate)
        {
            string sqlsrc = @" SELECT t1.LogUserName , t1.LogCreateDate, t2.LogTypeFriendlyName, t1.LogProperties ,t1.LogContent
                               FROM EventLog t1 INNER JOIN EventLogTypes t2 ON t1.LogTypeKey=t2.LogTypeKey ";
            string sql = "";
            if (loginname != "")
            {
                sql += " t1.LogUserName LIKE '%" + loginname + "%'";
            }
            if (logtypekey != "")
            {
                if (sql != "")
                {
                    sql += " AND ";
                }
                sql += " t1.LogTypeKey ='" + logtypekey + "'";
            }
            if (startdate != null && startdate != DateTime.MinValue)
            {
                if (sql != "")
                {
                    sql += " AND ";
                }
                sql += " t1.LogCreateDate>='" + startdate.ToString() + "'";
            }
            if (enddate != null && enddate != DateTime.MinValue)
            {
                if (sql != "")
                {
                    sql += " AND ";
                }
                if (enddate.TimeOfDay.ToString() == "00:00:00")
                {
                    enddate = enddate.AddHours(23).AddMinutes(59).AddSeconds(59);
                }
                sql += " t1.LogCreateDate<='" + enddate.ToString() + "'";
            }
            if (sql != "")
            {
                sqlsrc += " WHERE " + sql;
            }
            sqlsrc += " ORDER BY t1.LogCreateDate DESC";
            return SqlData.OpenSql(sqlsrc).Tables[0];
        }

        /// <summary>
        /// 日志查看的查询方法，此方法是带有分页功能的。 可以提高查询速度。但需要配合分页控件使用
        /// </summary>
        /// <param name="loginname"></param>
        /// <param name="logtypekey"></param>
        /// <param name="startdate"></param>
        /// <param name="enddate"></param>
        /// <param name="pagesize"></param>
        /// <param name="pageindex"></param>
        /// <param name="recordcount"></param>
        /// <returns></returns>
        public DataTable SelectInfoByPage(string loginname, string logtypekey, DateTime startdate, DateTime enddate, int start, int end, out decimal recordcount)
        {
            string strwhere = "";
            if (loginname != "")
            {
                strwhere += " EventLog.LogUserName LIKE '%" + loginname + "%'";
            }
            if (logtypekey != "")
            {
                if (strwhere != "")
                {
                    strwhere += " AND ";
                }
                strwhere += " EventLog.LogTypeKey ='" + logtypekey + "'";
            }
            if (startdate != null && startdate != DateTime.MinValue)
            {
                if (strwhere != "")
                {
                    strwhere += " AND ";
                }
                strwhere += " EventLog.LogCreateDate>='" + startdate.ToString() + "'";
            }
            if (enddate != null && enddate != DateTime.MinValue)
            {
                if (strwhere != "")
                {
                    strwhere += " AND ";
                }
                if (enddate.TimeOfDay.ToString() == "00:00:00")
                {
                    enddate = enddate.AddHours(23).AddMinutes(59).AddSeconds(59);
                }
                strwhere += " EventLog.LogCreateDate<='" + enddate.ToString() + "'";
            }
            recordcount = GetCount(strwhere);
            return GetByPage(start, end, strwhere);

        }
        /// <summary>
        /// 日志查看的查询方法，此方法是带有分页功能的。 可以提高查询速度。但需要配合分页控件使用
        /// </summary>
        /// <param name="loginname"></param>
        /// <param name="logtypekey"></param>
        /// <param name="startdate"></param>
        /// <param name="enddate"></param>
        /// <param name="pagesize"></param>
        /// <param name="pageindex"></param>
        /// <param name="recordcount"></param>
        /// <returns></returns>
        public DataTable SelectLogInfo(string loginname, string logtypekey, DateTime startdate, DateTime enddate)
        {
            string strwhere = "";
            string SQL = "select EventLog.LogGUID, EventLog.LogUserName, EventLog.LogCreateDate, EventLogTypes.LogTypeFriendlyName,  EventLog.LogContent "
                + " from EventLog inner join EventLogTypes on EventLog.LogTypeKey=EventLogTypes.LogTypeKey where EventLog.Active='1' ";
            if (!string.IsNullOrEmpty(loginname))
            {
                strwhere += " and EventLog.LogUserName LIKE '%" + loginname + "%'";
            }
            if (!string.IsNullOrEmpty(logtypekey))
            {
                strwhere += " and EventLog.LogTypeKey ='" + logtypekey + "'";
            }
            if (startdate != null && startdate != DateTime.MinValue)
            {
                strwhere += " AND EventLog.LogCreateDate>='" + startdate.ToString() + "'";
            }
            if (enddate != null && enddate != DateTime.MinValue)
            {
                if (enddate.TimeOfDay.ToString() == "00:00:00")
                {
                    enddate = enddate.AddHours(23).AddMinutes(59).AddSeconds(59);
                }
                strwhere += " AND EventLog.LogCreateDate<='" + enddate.ToString() + "'";
            }
            SQL += strwhere;
            SQL += "order by EventLog.LASTUPDATE_DT desc";
            return SqlData.OpenSql(SQL).Tables[0];

        }
        /// <summary>
        /// 根据条件获得记录数
        /// </summary>
        /// <param name="strwhere"></param>
        /// <returns></returns>
        public decimal GetCount(string strwhere)
        {
            string sql = " SELECT COUNT(1) FROM EventLog";
            if (strwhere != "")
            {
                sql += " WHERE 1=1 " + strwhere;
                sql = sql.Replace("t1.", "");
            }
            decimal tmp = -1;
            decimal.TryParse(SqlData.ExecuteScalar(sql).ToString(), out tmp);

            return tmp;
        }
        /// <summary>
        /// 分页提取相关数据
        /// </summary>
        /// <param name="PageSize"></param>
        /// <param name="PageIndex"></param>
        /// <param name="strWhere"></param>
        /// <param name="strGetFields"></param>
        /// <returns></returns>
        public DataTable GetByPage(decimal start, decimal end, string where)
        {

            string sql = "WITH OrderedOrders AS " +
                "(select t1.*, row_number() over(order by logcreatedate desc) as row,t2.LogTypeFriendlyName from EventLog t1 " +
                "INNER JOIN EventLogTypes t2 ON t1.LogTypeKey=t2.LogTypeKey " + where + " ) " +
                "SELECT * FROM OrderedOrders WHERE row BETWEEN {0} AND {1} ";


            return SqlData.OpenSql(string.Format(sql, start, end)).Tables[0];
        }

        public static void CreateNewEvent(LogType logType, string UserName, decimal userid, string content)
        {
            CreateNewEvent(logType.ToString(), UserName, userid.ToString(), content, DateTime.Now, Environment.MachineName.ToString(), "");
        }
    }
}
